/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include "StorageMgr.h"

using namespace std;

namespace {
const std::string MODULE_NAME = "StorageMgr";
const std::string STRING_LEVEL_SUPER_ADMIN = "1";
const std::string STRING_LEVEL_ADMIN = "2";
const std::string STRING_ROLE_SUPER_ADMIN = "1";
const std::string STRING_ROLE_ADMIN = "2";
}

HCS_PLUGIN_NAMESPACE_BEGIN

bool StorageMgr::GetStorageSystemInfo(const ControlDeviceInfo &info, StorageSysInfo &storageSysInfo,
    std::string &errorStr, bool isOpService)
{
    std::shared_ptr<ApiOperator> apiOperator = nullptr;
    if (ApiOperatorManager::GetInstance()->GetRestApiOperator(info, apiOperator, false) != SUCCESS) {
        ERRLOG("Get rest api operator failed.");
        return true;
    }

    if (apiOperator == nullptr) {
        ERRLOG("Api operator is null.");
        return false;
    }
    apiOperator->SetRetry(false);
    apiOperator->SetOpService(isOpService);
    if (apiOperator->GetSystemInfo(storageSysInfo, errorStr) != SUCCESS) {
        ERRLOG("Get system info failed.");
        return false;
    }

    // 管理员或超级管理员才能添加存储并注册HCS
    UserRoleLevel userRoleLevel;
    if (apiOperator->GetUserRoleAndLevel(
        info.m_userName, userRoleLevel, errorStr, storageSysInfo.m_productMode) != SUCCESS) {
        ERRLOG("Get user role and level failed.");
        return false;
    }

    std::set<std::string> levelInfo {STRING_LEVEL_SUPER_ADMIN, STRING_LEVEL_ADMIN};
    std::set<std::string> roleIDInfo {STRING_ROLE_SUPER_ADMIN, STRING_ROLE_ADMIN};
    // 部分版本无角色roleid概念，仅当roleid非空时才检查roleid
    if (levelInfo.find(userRoleLevel.m_level) == levelInfo.end() ||
        (!userRoleLevel.m_roleID.empty() && roleIDInfo.find(userRoleLevel.m_roleID) == roleIDInfo.end())) {
        ERRLOG("User info check failed. level: %s,roleid: %s",
            userRoleLevel.m_level.c_str(), userRoleLevel.m_roleID.c_str());
        return false;
    }

    return true;
}

HCS_PLUGIN_NAMESPACE_END